package com.boyadegroot.divelog.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.boyadegroot.divelog.R;
import com.boyadegroot.divelog.data.DiveLogData;
import com.boyadegroot.divelog.models.Diver;
import com.boyadegroot.divelog.ui.diver.DiverNew;
import com.boyadegroot.divelog.ui.diver.DiverTabs;

public class DiversPager extends ActionBarActivity {

    private static final String TAG = DiversPager.class.getName();

    private static final int NEW_DIVER_REQUEST = 1;
    private static final int DIVER_REQUEST = 2;

    private static final String STATE_CURRENT_ITEM = "currentItem";

    public static final String IN_DIVER = "diver";
    public static final String OUT_DIVER = "diver";

    private DiveLogData mData;
    private ViewPager mPager;
    private DiversAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Log.v(TAG, "onCreate(Bundle savedInstanceState)");
        setContentView(R.layout.pager_divers);
        FragmentManager fm = getSupportFragmentManager();
        // We create the DiveLogDb here, because we need the application's context to get an instance
        mData = DiveLogData.getInstance(this);
        // The adapter uses the database to count the amount of divers and create fragments that
        // shows the details of a diver.
        mAdapter = new DiversAdapter(fm, mData);
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        if (savedInstanceState != null) {
            int currentItem = savedInstanceState.getInt(STATE_CURRENT_ITEM);
            // Log.d(TAG, "Restoring current item = " + currentItem);
            mPager.setCurrentItem(currentItem, false);
        }
    }

    public void onNewDiverClick(MenuItem item) {
        // Log.v(TAG, "onNewDiverClick(MenuItem item)");
        Intent intent = new Intent(this, DiverNew.class);
        long currentDiverId = getCurrentDiverId();
        // Log.d(TAG, "Current diver id = " + currentDiverId);
        intent.putExtra(DiverNew.IN_DIVERID, currentDiverId);
        this.startActivityForResult(intent, NEW_DIVER_REQUEST);
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    }

    public void onDiverClick(View v) {
        // Log.v(TAG, "onDiverClick(View v)");
        Intent intent = new Intent(this, DiverTabs.class);
        Diver currentDiver = getCurrentDiver();
        // Log.d(TAG, "Diver to show: " + currentDiver);
        intent.putExtra(DiversPager.IN_DIVER, currentDiver);
        this.startActivityForResult(intent, DIVER_REQUEST);
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    }

    private Diver getCurrentDiver() {
        int currentPosition = mPager.getCurrentItem();
        Diver currentDiver = mData.getDiverByPosition(currentPosition);
        return currentDiver;
    }
    
    private long getCurrentDiverId() {
        int currentPosition = mPager.getCurrentItem();
        Diver currentDiver = mData.getDiverByPosition(currentPosition);
        long currentDiverId = currentDiver.getId();
        return currentDiverId;
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // Log.v(TAG, "onSaveInstanceState(Bundle outState)");
        int currentItem = mPager.getCurrentItem();
        // Log.d(TAG, "Saving current item = " + currentItem);
        outState.putInt(STATE_CURRENT_ITEM, currentItem);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Log.v(TAG, "onCreateOptionsMenu(Menu menu)");
        getMenuInflater().inflate(R.menu.menu_diverspager, menu);
        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Log.v(TAG, "onActivityResult(int requestCode, int resultCode, Intent data)");
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == NEW_DIVER_REQUEST) {
            // Log.d(TAG, "requestCode == NEW_DIVER_REQUEST");
            // User saved a new diver, so notify data changed
            if (resultCode == RESULT_OK) {
                // Log.d(TAG, "resultCode == RESULT_OK");
                mAdapter.notifyDataSetChanged();
            }
            // We always get back the id of the diver to show
            // This could be the new diver (on Save) or the previously selected one (on Cancel)
            if (data == null) {
                throw new Error("New diver returned without returning data");
            }
            long diverId = data.getLongExtra(DiverNew.OUT_DIVERID, -1);
            if (diverId == -1) {
                throw new Error("New diver returned with data, but no diverId");
            }
            int position = mData.getDiverPosition(diverId);
            if (position == -1) {
                throw new Error("Could not get position of diver with id " + diverId);
            }
            // Log.d(TAG, "Showing diver in position " + position);
            mPager.setCurrentItem(position, false);
        } else if (requestCode == DIVER_REQUEST) {
            // TODO Do something when returning from Diver
        }
    }
}